﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json.Linq;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.SalInvoiceDownloadFile6
{
    [Description("销售增值税专票下载文件"), HotUpdate]
    public class SalVatSpecialInvoiceDownloadFile : AbstractListPlugIn
    {
        public string btype { get; set; } = "销售增值税专票下载文件";
        public string logType { get; set; } = "销售增值税专票下载文件";
        public string directory { get; set; } = "";
        public string txtpath { get; set; } = @"C:\InvoiceTxt\TXT";
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            //下载发票文件
            if (e.BarItemKey.EqualsV1("btnDownloadInvoiceFile"))
            {
                try
                {
                    var lv = this.View as IListView;
                    if (lv == null)
                    {
                        View.ShowErrMessage($@"无数据!!!");
                        return;
                    }
                    var selectedRows = lv.SelectedRowsInfo;
                    if (selectedRows == null || selectedRows.Count == 0)
                    {
                        this.View.ShowMessage("当前没有行被选中！");
                        return;
                    }
                    List<int> ids = selectedRows.Select(x => x.PrimaryKeyValue.ToStringV1().ToInt32V1()).Distinct().ToList();
                    if (ids.Count < 1)
                    {
                        View.ShowErrMessage($@"选择行为空!!!");
                        return;
                    }
                    DownloadFiles(ids);
                }
                catch (Exception ex)
                {
                    View.ShowErrMessage($@"异常SI001【{ex.Message}】");
                    return;
                }
            }
        }
        public void DownloadFiles(List<int> idList)
        {
            List<InvoiceData> dataList = new List<InvoiceData>();
            int size = 2000;
            int icount = idList.Count <= size ? 1 : idList.Count % size > 0 ? idList.Count / size + 1 : idList.Count / size;
            for (int i = 0; i < icount; i++)
            {
                List<int> ids = idList.Skip(size * i).Take(size).ToList();
                string sql = $@"/*dialect*/ select 
id=fp.FID
,billNo=fp.FBILLNO
,invoiceNumber=fpO.FIVNUMBER --发票号码
,invoiceDate=CONVERT(varchar(50),fp.FINVOICEDATE,23) --发票日期
,invoiceTittle=fp.FINVOICETITLE  --发票抬头
,amount=fp.FAFTERTOTALTAXFOR --发票价税合计
,networkAddress=fpO.FPDFURLCOPY
from T_IV_SALESIC fp
left join T_IV_SALESIC_O fpO on fp.FID=fpO.FID
where fp.FID in ({string.Join(",", ids)})
and ISNULL(fp.FBILLNO,'')<>''
and ISNULL(fpO.FPDFURLCOPY,'')<>''";
                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
                if (datas != null && datas.Count > 0)
                {
                    List<InvoiceData> dlist = datas.DynamicObjectCollectionToDataList<InvoiceData>();
                    dataList.AddRange(dlist);
                }
            }
            if (dataList.Count < 1)
            {
                View.ShowErrMessage($@"不存在符合条件的发票单!!!");
                return;
            }
            //写入exccel

            XSSFWorkbook workbook = new XSSFWorkbook();
            //工作簿
            XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("发票信息");
            sheet.DefaultColumnWidth = 20;
            sheet.DefaultRowHeight = 30 * 20;
            //创建列名  第一行
            List<string> cnames = new List<string>() { "单号", "发票号码", "发票日期", "发票抬头", "发票价税合计", "电子发票地址" };
            XSSFRow rowColumn = (XSSFRow)sheet.CreateRow(0);
            for (int j = 0; j < cnames.Count; j++)
            {
                XSSFCell cellColumn = (XSSFCell)rowColumn.CreateCell(j);
                cellColumn.SetCellValue(cnames[j].ToStringV1());
            }
            //创建数据行
            for (int i = 0; i < dataList.Count; i++)
            {
                InvoiceData data = dataList[i];
                XSSFRow rowData = (XSSFRow)sheet.CreateRow(i + 1);
                //单号
                XSSFCell cellData0 = (XSSFCell)rowData.CreateCell(0);
                cellData0.SetCellValue(data.billNo);
                //发票号码
                XSSFCell cellData1 = (XSSFCell)rowData.CreateCell(1);
                cellData1.SetCellValue(data.invoiceNumber);
                //发票日期
                XSSFCell cellData2 = (XSSFCell)rowData.CreateCell(2);
                cellData2.SetCellValue(data.invoiceDate);
                //发票抬头
                XSSFCell cellData3 = (XSSFCell)rowData.CreateCell(3);
                cellData3.SetCellValue(data.invoiceTittle);
                //发票价税合计
                XSSFCell cellData4 = (XSSFCell)rowData.CreateCell(4);
                cellData4.SetCellValue(data.amount.ToString("0.00"));
                //电子发票地址
                XSSFCell cellData5 = (XSSFCell)rowData.CreateCell(5);
                cellData5.SetCellValue(data.networkAddress);
            }

            if (!Directory.Exists(txtpath))
                Directory.CreateDirectory(txtpath);
            string txtname = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
            string txtFullPath = txtpath + "\\" + txtname;
            if (File.Exists(txtFullPath))
            {
                File.Delete(txtFullPath);
                File.Create(txtFullPath).Close();
            }
            else
                File.Create(txtFullPath).Close();

            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();
            //保存为Excel文件  
            using (FileStream fs = new FileStream(txtFullPath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }


            DynamicFormShowParameter formPa = new DynamicFormShowParameter();
            //formPa.FormId = "UUEI_ChoseInvoiceDirectoryForm";
            formPa.FormId = "RLKX_ChoseInvoiceDirectoryForm";//正式环境
            formPa.CustomParams.Add("txtname", txtname);
            View.ShowForm(formPa);
        }

    }
    public class InvoiceData
    {
        public int id { get; set; }
        public string billNo { get; set; }
        public string invoiceNumber { get; set; }
        public string invoiceDate { get; set; }
        public string invoiceTittle { get; set; }
        public decimal amount { get; set; }
        public string networkAddress { get; set; }
        public string filePath { get; set; }
        public bool status { get; set; }
        public string msg { get; set; }
    }

}
